package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var localOpenAccountLogger *logrus.Logger

// InitLocalAccountOpenLogger 移除 init() 函数，改为显式初始化函数
func InitLocalAccountOpenLogger() {
	// 确保在 common 初始化后调用
	localOpenAccountLogger = core.InitLogger(common.LogsErrorMap[14])
}

// HugeLocalOpenAccount 消息结构体
type HugeLocalOpenAccount struct {
	AccountName       string
	MerchantID        string
	AccountID         string
	WithoutID         int64
	Contact           string
	MobilePhoneNumber string
	Email             string
	Province          string
	City              string
}

type HugeLocalOpenAccountService struct {
}

func (s *HugeLocalOpenAccountService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {

	var msg = &models.Msg{}

	fmt.Println("localOpenAccountLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		localOpenAccountLogger.Error("巨量本地推销售获取数据失败", common.LogsErrorMap[2], msgId, err)
		return err
	}

	localOpenAccountLogger.Info("localOpenAccountLogger", "原始结构：", content)

	// 处理需要的数据结构
	result, err := s.analyzeContent(content)
	if err != nil {
		localOpenAccountLogger.Error(err)
		return err
	}

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	localOpenAccountLogger.Info("localOpenAccountLogger", result, "移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, err := rdb.Get(ctx, "laravel_database_oead_adv_cookies").Result()

	fmt.Println("localOpenAccountLogger", "Cookies:", cookies)
	// 第一步 校验商家是否授权
	_, err = s.checkAuthorization(result.MerchantID, cookies)
	if err != nil {
		localOpenAccountLogger.Error("校验商家授权", result.MerchantID, err)
		return fmt.Errorf("媒体提示1：%v", err)
	}

	// 第二步 获取证件号码
	documentInfo, err := s.getDocumentNumber(result.MerchantID, cookies)
	if err != nil {
		localOpenAccountLogger.Warnf("获取证件号码失败: %v", err)
		return errors.New("媒体提示4：" + err.Error())
	}

	// 第五步 查询直客信息
	searchResponse, err := s.getSearchWithout(documentInfo.Data.LifeAccountName, documentInfo.Data.LicenseNo, documentInfo.Data.LicenseType, cookies)
	if err != nil {
		localOpenAccountLogger.Warnf("获取直客信息失败: %v", err)
		return errors.New("媒体提示5：" + err.Error())
	}

	var industryId int64
	var smallIndustryId int64
	for _, value := range searchResponse.Data {
		if value.CustomerID == result.WithoutID {
			industryId = value.IndustryId
			smallIndustryId = value.SmallIndustryId
			break
		}
	}

	if industryId == 0 || smallIndustryId == 0 {
		return errors.New("媒体提示5：未找到证件号码，请检查证件号码是否正确！")
	}

	accountName := result.AccountName + "-yx"
	// 第六步 提交复制户信息

	err = s.checkCopy(1, accountName, cookies)
	if err != nil {
		return errors.New("提交复制户失败：" + err.Error())
	}

	makeData := map[string]interface{}{
		"localAccountType":     1,
		"company":              documentInfo.Data.LifeAccountName,
		"license_type":         documentInfo.Data.LicenseType,
		"license_no":           documentInfo.Data.LicenseNo,
		"agentId":              "1793206833630283",
		"name":                 accountName,
		"shopId":               result.MerchantID,
		"contacter":            result.Contact,
		"phonenumber":          result.MobilePhoneNumber,
		"email":                result.Email,
		"systemOrigin":         104,
		"accountCate":          8,
		"first_industry_code":  industryId,
		"second_industry_code": smallIndustryId,
		"license_country":      17487275,
		"license_country_name": "中国",
		"license_province":     result.Province,
		"license_city":         result.City,
		"license_type_name":    documentInfo.Data.LicenseTypeDesc,
	}

	localOpenAccountLogger.Info("组装提交数据：", makeData)

	// 第七步 同意开户
	createSuccess, err := s.createFirstState(makeData, cookies)
	if err != nil {
		localOpenAccountLogger.Error("提交开户数据失败：", err)
		return errors.New("开户失败：" + err.Error())
	}

	if err := BendiSendText(msg.Content+"\n-----------------------------------\n开户成功："+createSuccess.AdvName, msg.RoomID, msg.Sender); err != nil {
		localOpenAccountLogger.Errorf("开户成功发送消息失败: %v", err)
		return errors.New("开户成功发送消息失败: " + err.Error())
	}

	createData := &models.NewOpenAccountRecord{
		SubAccountName:  result.AccountName,
		OeMerchantID:    result.MerchantID,
		AccountID:       createSuccess.AdvId,
		OeWithoutID:     result.WithoutID,
		OeContactPerson: result.Contact,
		OePhone:         result.MobilePhoneNumber,
		OeEmail:         result.Email,
		Type:            3,
		Status:          1,
	}

	err = common.DB.Create(createData).Error
	if err != nil {
		localOpenAccountLogger.Errorf("数据入库异常: %v, 数据: %v", err, createData)
		if err := BendiSendText(msg.Content+"\n-----------------------------------\n数据入库异常，请检查日志", msg.RoomID, msg.Sender); err != nil {
			localOpenAccountLogger.Errorf("入库消息失败: %v", err)
			return errors.New("入库消息失败: " + err.Error())
		}
	}

	return nil
}

// 同意开户
func (s *HugeLocalOpenAccountService) createFirstState(data map[string]interface{}, cookies string) (*createResponseData, error) {
	createUrl := "https://agent.oceanengine.com/agent/adv-create/add/first/state/"

	var createRes createResponse
	err := s.SendCurlRequest(createUrl, data, cookies, "POST", "", &createRes)
	if err != nil {
		localOpenAccountLogger.Infof("createFirstState请求失败: %v", err)
		return nil, fmt.Errorf("创建开户失败1: %v", err)
	}

	localOpenAccountLogger.Info("createFirstState原始响应: %+v", createRes)

	if createRes.Code != 0 {
		localOpenAccountLogger.Info("createRes.Code:", createRes.Msg, "返回参数:", createRes)
		return nil, fmt.Errorf("创建开户失败2: %v", createRes.Msg)
	}

	var res createResponseData
	err = json.Unmarshal(createRes.Data, &res)
	if err != nil {
		return nil, fmt.Errorf("创建开户失败3解析失败: %v", err)
	}

	if res.ErrorState != 0 {
		localOpenAccountLogger.Info("ErrorState:", res.Msg, "返回参数:", res)
		return nil, fmt.Errorf("创建开户失败3: %v", res.Msg)
	}

	return &res, nil
}

// 提交复制户信息
func (s *HugeLocalOpenAccountService) checkCopy(num int, accountName, cookies string) error {
	copyUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/name/check/?accountCate=%d&advName=%s", num, accountName)

	var copyRes checkCopyResponse
	err := s.SendCurlRequest(copyUrl, nil, cookies, "GET", "", &copyRes)
	if err != nil {
		localOpenAccountLogger.Error("发送复制请求失败1:", err, "返回结果：", copyRes)
		return fmt.Errorf("发送复制请求失败1: %v", err)
	}

	localOpenAccountLogger.Info("复制请求结果:", copyRes)

	if copyRes.Code != 0 {
		localOpenAccountLogger.Error("发送复制请求失败2:", err, "返回结果：", copyRes)
		return fmt.Errorf("发送复制请求失败2: %v", err)
	}

	return nil
}

// 获取直客信息
func (s *HugeLocalOpenAccountService) getSearchWithout(customerName, licenseNo, licenseType, oeAdCookies string) (*SearchWithoutResponse, error) {
	sprintfUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/customer/query?customerName=%s&licenseNo=%s&licenseType=%s", customerName, licenseNo, licenseType)

	var response SearchWithoutResponse
	err := s.SendCurlRequest(sprintfUrl, nil, oeAdCookies, "GET", "", &response)
	if err != nil {
		localOpenAccountLogger.Errorf("获取直客信息失败: %v", err)
		return nil, err
	}

	// 记录完整响应
	localOpenAccountLogger.Infof("getSearchWithout获取直客完整信息: %+v", response)

	// 检查返回码不为0的情况
	if response.Code != 0 {
		localOpenAccountLogger.Warnf("getSearchWithout获取直客信息失败: %s", response.Msg)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 检查data为空的情况
	if len(response.Data) == 0 {
		localOpenAccountLogger.Warnf("getSearchWithout未找到对应的授权信息: %s", response.Msg)
		return nil, fmt.Errorf("未找到直客信息: %s", response.Msg)
	}

	return &response, nil
}

// 获取证件号码
func (s *HugeLocalOpenAccountService) getDocumentNumber(lifeAccountId string, cookies string) (*DocumentNumberResponse, error) {
	documentUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/localPromotion/query?lifeAccountId=%s", lifeAccountId)

	var result DocumentNumberResponse
	err := s.SendCurlRequest(documentUrl, nil, cookies, "GET", "", &result)
	if err != nil {
		return nil, err
	}

	if result.Code != 0 {
		localOpenAccountLogger.Error("获取证件号码失败", result)
		return nil, fmt.Errorf("获取证件号码失败: %s", result.Msg)
	}

	return &result, nil
}

// 校验商家是否授权
func (s *HugeLocalOpenAccountService) checkAuthorization(lifeAccountId, cookie string) (*Account, error) {
	checkUrl := "https://agent.oceanengine.com/agent/optimize/localPromotion/list?lifeAccountId=" + lifeAccountId + "&page=1&size=10"

	var req Response
	err := s.SendCurlRequest(checkUrl, nil, cookie, "GET", "", &req)
	if err != nil {
		localOpenAccountLogger.Errorf("checkAuthorization获取商家是否授权: %v", err)
		return nil, err
	}

	localOpenAccountLogger.Info("记录完整的返回信息：", req)

	if req.Code != 0 {
		localOpenAccountLogger.Error("获取商家是否授权失败:", req)
		return nil, fmt.Errorf(req.Msg)
	}

	if req.Data.Total == 0 {
		localOpenAccountLogger.Error("checkAuthorization未找到对应的授权信息：", req)
		return nil, errors.New("媒体后台中未查询到授权信息")
	}

	account := req.Data.List[0]
	if account.AuthorizedStatus != 2 {
		localOpenAccountLogger.Info("checkAuthorization客户暂未同意授权：", req)
		//statusName := "未知状态"
		//if name, ok := accountStatus[account.AuthorizedStatus]; ok {
		//	statusName = name
		//}
		return nil, nil
	}

	return &account, nil
}

// SendCurlRequest 发送HTTP请求
func (s *HugeLocalOpenAccountService) SendCurlRequest(url string, postData interface{}, xhsCookies string, method string, oeCsrfToken string, result interface{}) error {
	// 创建请求上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 序列化POST数据
	var bodyReader io.Reader
	if postData != nil {
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return fmt.Errorf("JSON序列化失败: %v", err)
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Cookie", xhsCookies)
	if oeCsrfToken != "" {
		req.Header.Set("Cg-Csrf-Token", oeCsrfToken)
	}

	// 创建自定义客户端
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取响应失败: %v", err)
	}

	localOpenAccountLogger.Info("获取后得参数格式：", string(respBody))

	if result != nil {
		if err := json.Unmarshal(respBody, &result); err != nil {
			return fmt.Errorf("JSON解析失败: %v", err)
		}
	}
	return nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *HugeLocalOpenAccountService) analyzeContent(content []string) (*HugeLocalOpenAccount, error) {
	// 初始化结果变量
	var accountName string
	var merchantID string
	var withoutIDStr string
	var withoutID int64
	var contact string
	var mobilePhoneNumber string
	var email string
	var province string
	var city string

	// 遍历内容行
	for _, line := range content {
		// 账户名称
		if strings.HasPrefix(line, "账户名称:") {
			accountName = strings.TrimSpace(strings.TrimPrefix(line, "账户名称:"))
		}
		// 商家ID
		if strings.HasPrefix(line, "商家ID:") {
			merchantID = strings.TrimSpace(strings.TrimPrefix(line, "商家ID:"))
		}
		// 直客ID
		if strings.HasPrefix(line, "直客ID:") {
			withoutIDStr = strings.TrimSpace(strings.TrimPrefix(line, "直客ID:"))
		}
		// 联系人姓名
		if strings.HasPrefix(line, "联系人姓名:") {
			contact = strings.TrimSpace(strings.TrimPrefix(line, "联系人姓名:"))
		}
		// 手机号
		if strings.HasPrefix(line, "手机号:") {
			mobilePhoneNumber = strings.TrimSpace(strings.TrimPrefix(line, "手机号:"))
		}
		// 邮箱
		if strings.HasPrefix(line, "邮箱:") {
			email = strings.TrimSpace(strings.TrimPrefix(line, "邮箱:"))
		}
		// 省
		if strings.HasPrefix(line, "省:") {
			province = strings.TrimSpace(strings.TrimPrefix(line, "省:"))
		}
		// 市
		if strings.HasPrefix(line, "市:") {
			city = strings.TrimSpace(strings.TrimPrefix(line, "市:"))
		}
	}

	if accountName == "" || merchantID == "" || contact == "" || email == "" || mobilePhoneNumber == "" || province == "" || city == "" {
		localOpenAccountLogger.Warn("请检查参数是否正确")
		return nil, errors.New("解析参数失败: 请检查参数是否正确")
	}

	// 转换 withoutID 为 int64
	var err error
	withoutID, err = strconv.ParseInt(withoutIDStr, 10, 64)
	if err != nil {
		localCopyAccountLogger.Errorf("直客ID转换失败: %v", err)
		return nil, fmt.Errorf("直客ID格式错误: %w", err)
	}

	return &HugeLocalOpenAccount{
		AccountName:       accountName,
		MerchantID:        merchantID,
		WithoutID:         withoutID,
		Contact:           contact,
		MobilePhoneNumber: mobilePhoneNumber,
		Email:             email,
		Province:          province,
		City:              city,
	}, nil
}
